import { useStore } from "vuex";
import { computed } from "vue";
export const useCommonCartEffect = (shopId) => {
  const store = useStore();
  const cartList = store.state.cartList;
  const changeItemToCart = (shopId, productId, productInfo, num) => {
    store.commit("changeItemToCart", { shopId, productId, productInfo, num });
  };
  const productList = computed(() => {
    const productList = cartList[shopId]?.productList || {};
    const notEmptyProductList = {};
    for (const i in productList) {
      if (productList[i].count > 0) {
        notEmptyProductList[i] = productList[i];
      }
    }
    return notEmptyProductList;
  });
  const shopName = computed(() => {
    const shopName = cartList[shopId]?.shopName || "";
    return shopName;
  });
  const caculation = computed(() => {
    // 所有要循环的放在一起
    const result = {
      totalCount: 0,
      totalPrice: 0,
      allCheckedStatus: true,
    };
    const products = cartList[shopId]?.productList;
    if (products) {
      for (const i in products) {
        result.totalCount += products[i].count; // 计算总数
        const thisPrice = products[i].price * products[i].count;
        if (products[i].checked) {
          result.totalPrice += thisPrice; // 当前购物车中勾选的所有的商品总价
        }
        if (products[i].count > 0 && !products[i].checked) {
          // 全选按钮的状态
          // 购物车中有东西但未选中
          result.allCheckedStatus = false;
        }
      }
    }
    result.totalPrice = result.totalPrice.toFixed(2);
    return result;
  });
  return { cartList, changeItemToCart, productList, shopName, caculation };
};
